package com.jj.net.tcp;

import com.jj.config.Constants;
import com.jj.net.ChannelListener;
import com.jj.net.Context;
import com.jj.net.Message;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GameIOHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(GameIOHandler.class);

    private ChannelListener eventListener;

    public GameIOHandler(ChannelListener listener){
        this.eventListener = listener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        logger.debug("channel active:{}", ctx.channel().remoteAddress());
        TCPContextImpl context = new TCPContextImpl(ctx);
        eventListener.onOpen(context);
        ctx.channel().attr(Constants.TCP_CONTEXT_ATTRIBUTE_KEY).set(context);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        logger.debug("channel inactive:{}", ctx.channel().remoteAddress());
        Context context = ctx.channel().attr(Constants.TCP_CONTEXT_ATTRIBUTE_KEY).get();
        eventListener.onClosed(context);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("channel read {} from {}", msg.getClass().getSimpleName(), ctx.channel().remoteAddress());
        Context context = ctx.channel().attr(Constants.TCP_CONTEXT_ATTRIBUTE_KEY).get();
        eventListener.onRcv((Message) msg, context);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("exception", cause);
        logger.debug("close {}", ctx.channel().remoteAddress());
    }


}
